//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
// 

#include "tractorTraceReader.h"
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iterator>

int tractorTraceReader::searchInTraces(int sender, int receiver, simtime_t t_simul) {
    std::vector<int> indexes = indexOfNode(receiver);
    for (unsigned int i = 0; i < indexes.size(); i++) {
        double t_translated = convertSimulTimestamp(t_simul, traces[indexes[i]].firstTimestamp(), traces[indexes[i]].lastTimestamp());
        EV<< "receiver = "<< receiver <<"\n" << static_cast<int>(t_translated) << endl;
        int j = traces[indexes[i]].indexForTime(t_translated);
        while(j != -1 && j < traces[indexes[i]].numberTraces()){
            if(sender == traces[indexes[i]].senderAt(j) && receiver == traces[indexes[i]].receiverAt(j))
                return 1;
            else
                j++;
        }
    }
    return 0;
}

double tractorTraceReader::convertSimulTimestamp(simtime_t t_simul, int t_real_first, int t_real_last) {
    double mm_t_simul = floor(t_simul.dbl() * 1000.0);
    double t_translated = mm_t_simul + t_real_first;
    if (t_translated < t_real_first || t_translated > t_real_last){
        int int_t_translated = (static_cast<int>(t_translated) % (t_real_last - t_real_first)) + t_real_first;
        t_translated = int_t_translated * 1.0;
    }
    return t_translated;
}

std::vector<int> tractorTraceReader::indexOfNode(int node) {
    std::vector<int> indexes;
    for (unsigned int i = 0; i < idFileList.size(); i++) {
        if (idFileList[i] == node)
            indexes.push_back(i);
    }
    return indexes;
}


